﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Framework.Core.Cryptography
{
    public sealed class AssymetricDecryptionReader : IDisposable
    {
        private readonly BinaryReader reader;
        private readonly RSACryptoServiceProvider rsa;
        private readonly Stream source;

        public AssymetricDecryptionReader(Stream source, string application, string user)
            : this(source, application, user, new RsaCryptoServiceProviderFactory())
        {
        }

        private AssymetricDecryptionReader(Stream source,
                                           string application,
                                           string user,
                                           IRsaCryptoServiceProviderFactory rsaCryptoServiceProviderFactory)
        {
            this.source = source;
            rsa = rsaCryptoServiceProviderFactory.Create(application, user);
            reader = new BinaryReader(source);
        }

        void IDisposable.Dispose()
        {
            ((IDisposable)rsa).Dispose();
            ((IDisposable)reader).Dispose();
        }

        public string ReadToEnd()
        {
            source.Seek(0, SeekOrigin.Begin);
            var encryptedData = reader.ReadBytes((int)source.Length);

            return Encoding.UTF8.GetString(rsa.Decrypt(encryptedData, false));
        }
    }
}
